<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>事件的传递和处理</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        /*.box1 {
            width: 200px;
            height: 200px;
            background-color: red;
            position: relative;
        }

        .box2 {
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: green;
            top: 50px;
            left: 50px;
        }*/
        .box1 {
            width: 200px;
            height: 200px;
            background-color: red;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .box2 {
            width: 100px;
            height: 100px;
            background-color: green;

        }
    </style>
</head>
<body>
<div id="change" class="change">
    <div class="box1" data-on:click="box1clicked">
        <!--.stop 修饰符 用来阻止事件的冒泡-->
        <div class="box2" data-on:click.stop="box2clicked"></div>
    </div>
</div>

<script>
    function box1clicked() {
        console.log("点击了 外部 区域");
    }

    function box2clicked() {
        console.log("点击了 内部 区域");
    }

    function event_handling(element) {
        // 获取该元素所有的属性
        let attributeNames = element.getAttributeNames();

        for (let i = 0; i < attributeNames.length; i++) {
            if (attributeNames[i].indexOf("data-on:") !== -1) {
                let start = attributeNames[i].indexOf(":");
                let end = attributeNames[i].indexOf(".");

                let event_name = null

                let modifier = null
                if (end === -1) {
                    event_name = attributeNames[i].substring(start + 1);
                } else {
                    event_name = attributeNames[i].substring(start + 1, end);
                    modifier = attributeNames[i].substring(end + 1);
                }

                let event_func = element.getAttribute(attributeNames[i]);
                console.log(event_func);
                console.log(event_name);
                console.log(modifier);

                element.addEventListener(event_name, function (event) {
                    eval(event_func + "()")
                    if (modifier === "stop") {
                        event.stopPropagation()
                    }
                })

                element.removeAttribute(attributeNames[i])
            }
        }
    }

    let outer = document.querySelector("#change .box1");
    let inner = document.querySelector("#change .box2");

    event_handling(inner)
    event_handling(outer)


</script>
</body>
</html>